from flask import abort
from flask import current_app
from flask import g, jsonify
from flask import redirect
from flask import render_template
from flask import request
from flask import session

from info import constants
from info import db
from info.models import Category, News, User
from info.utils.common import user_login_data
from info.utils.image_storage import storage
from info.utils.response_code import RET
from . import user_blue


@user_blue.route('/other_news_list')
def other_news_list():
    """返回指定用户的发布的新闻"""

    # 1. 取参数
    other_id = request.args.get("user_id")
    page = request.args.get("p", 1)

    # 2. 判断参数
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        other = User.query.get(other_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询失败")

    if not other:
        return jsonify(errno=RET.NODATA, errmsg="当前用户不存在")

    try:
        paginate = other.news_list.paginate(page, constants.USER_COLLECTION_MAX_NEWS, False)
        # 获取当前页数据
        news_li = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询失败")

    news_dict_li = []
    for news_item in news_li:
        news_dict_li.append(news_item.to_basic_dict())

    data = {
        "news_list": news_dict_li,
        "total_page": total_page,
        "current_page": current_page
    }
    return jsonify(errno=RET.OK, errmsg="OK", data=data)


@user_blue.route('/other_info')
@user_login_data
def other_info():

    user = g.user

    # 去查询其他人的用户信息
    other_id = request.args.get("user_id")

    if not other_id:
        abort(404)

    # 查询指定id的用户信息
    try:
        other = User.query.get(other_id)
    except Exception as e:
        current_app.logger.error(e)

    if not other:
        abort(404)

    is_followed = False
    # if 当前新闻有作者，并且 当前登录用户已关注过这个用户
    if other and user:
        # if user 是否关注过 news.user
        if other in user.followed:
            is_followed = True

    data = {
        "is_followed": is_followed,
        "user": g.user.to_dict() if g.user else None,
        "other_info": other.to_dict()
    }
    return render_template('news/other.html', data=data)


@user_blue.route('/user_follow')
@user_login_data
def user_follow():
    # 获取页数
    p = request.args.get("p", 1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        # 当转类型失败时,在给p赋一个值,防止查询出现错误
        p = 1

    user = g.user

    follows = []
    # 这里的current_page是当查询数据库的时候,如果出现错误.就使用当前的页码,也是防止查询出现错误,导致无法返回
    current_page = 1
    total_page = 1
    try:
        paginate = user.followed.paginate(p, constants.USER_FOLLOWED_MAX_COUNT, False)
        # 获取当前页数据
        follows = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    user_dict_li = []

    for follow_user in follows:
        user_dict_li.append(follow_user.to_dict())
    data = {"users": user_dict_li, "total_page": total_page, "current_page": current_page}
    return render_template('news/user_follow.html', data=data)


# 个人发布的新闻的列表
@user_blue.route('/news_list')
@user_login_data
def news_list():
    # 一.获取参数
    page = request.args.get('page', 1)

    # 二. 校验参数
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    # 三.逻辑处理
    user = g.user
    news_models = []
    current_page = 1
    total_page = 1
    try:
        paginate = News.query.filter(News.user_id == user.id).paginate(page, 1, False)
        # 获取分页数据
        news_models = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages

    except Exception as e:
        current_app.logger.error(e)

    news_list = []
    for news in news_models:
        # 需要返回带拒绝原因的
        news_list.append(news.to_review_dict())

    # 四. 返回数据
    data = {
        'news_list': news_list,
        'current_page': current_page,
        'total_page': total_page
    }
    return render_template('news/user_news_list.html', data=data)


# 发布新闻
@user_blue.route('/news_release', methods=['GET', 'POST'])
@user_login_data
def news_release():
    # GET 请求传递分类数据并渲染模板
    if request.method == 'GET':
        # 查询分类
        category_models = []

        try:
            category_models = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="数据库错误")

        # 模型转字典
        category_list = []
        for category in category_models:
            category_list.append(category.to_dict())

        # 删除第一个元素
        category_list.pop(0)
        data = {
            'category_list': category_list
        }

        return render_template('news/user_news_release.html', data=data)

    # POST请求,发布新闻
    # 一.获取参数
    title = request.form.get("title")
    source = "个人发布"
    digest = request.form.get("digest")
    content = request.form.get("content")
    index_image = request.files.get("index_image")
    category_id = request.form.get("category_id")

    # 二. 校验参数
    # 1. 完整性
    if not all([title, source, digest, content, index_image, category_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    # 2.读取图片
    try:
        image_data = index_image.read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    # 3.再次查询分类模型, 因为有可能在发表文章的过程中新闻的模型已经不存在了
    try:
        category_id = int(category_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        category_model = Category.query.get(category_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询数据库错误')

    if not category_model:
        return jsonify(errno=RET.NODATA, errmsg='新闻分类不存在')

    # 三.逻辑处理
    # 1. 上传图片到七牛云
    try:
        image_name = storage(image_data)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库错误")

    # 2.创建新闻模型
    news = News()
    news.title = title
    news.digest = digest
    news.source = source
    news.content = content
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + image_name
    news.category_id = category_id
    news.user_id = g.user.id

    # 给新闻设置待审核状态,1代表待审核状态
    news.status = 1

    # 3.保存到数据库
    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="保存到数据库错误")

    # 四.返回数据,这里会跳转到新闻发表页面,但是交给前端处理
    return jsonify(errno=RET.OK, errmsg="发布成功，等待审核")


# 修改用户密码
@user_blue.route('/pass_info', methods=['GET', 'POST'])
@user_login_data
def pass_info():
    if request.method == "GET":
        return render_template('news/user_pass_info.html')

    # POST请求,修改密码
    # 1.获取参数
    old_password = request.json.get("old_password")
    new_password = request.json.get("new_password")

    if not all([old_password, new_password]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    # 2.验证老密码
    user = g.user
    if not user.check_password(old_password):
        return jsonify(errno=RET.PWDERR, errmsg="原密码错误")

    # 3.更新新密码
    user.password = new_password

    # 4.提交数据库
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存数据失败")

    # 返回数据
    return jsonify(errno=RET.OK, errmsg="保存成功")


# 用户收藏, 只有get请求
@user_blue.route('/collection')
@user_login_data
def collection():
    # 一.获取参数
    page = request.args.get('page', 1)

    # 二.校验参数
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        # 因为此时需要渲染网页, 不能返回错误的数据给用户,我们可以对错误的数据进行默认赋值
        page = 1

    # 三.逻辑处理
    user = g.user

    # 进行分页数据查询
    try:
        paginate = user.collection_news.paginate(page, constants.USER_COLLECTION_MAX_NEWS, False)
        # 获取分页数据
        collection_models = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages

    except Exception as e:
        current_app.logger.error(e)
        collection_models = []
        current_page = 1
        total_page = 1

    collection_list = []
    for collection in collection_models:
        collection_list.append(collection.to_dict())

    # 四.返回数据
    data = {
        'collection_list': collection_list,
        'current_page': current_page,
        'total_page': total_page
    }
    return render_template('news/user_collection.html', data=data)


# 上传头像
@user_blue.route('/pic_info', methods=['GET', 'POST'])
@user_login_data
def pic_info():
    user = g.user
    if request.method == 'GET':
        return render_template('news/user_pic_info.html', data={'user': user.to_dict()})

    # 上传图像,POST请求
    # 一.获取参数
    try:
        avatar_data = request.files.get('avatar').read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 二. 上传到七牛云&保存到数据库
    # 2.1上传到七牛云
    try:
        avatar_name = storage(avatar_data)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="上传七牛云错误")

    # 2.2保存到数据库
    # 存储时可以不存前缀
    user.avatar_url = avatar_name

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库错误")

    # 三.返回数据
    return jsonify(errno=RET.OK, errmsg="OK", data={"avatar_url": constants.QINIU_DOMIN_PREFIX + avatar_name})


# 获取用户基本信息页面
@user_blue.route('/base_info', methods=['GET', 'POST'])
@user_login_data
def base_info():
    user = g.user
    # 在这里不再需要判断用户的是否登陆了,因为这是在渲染大模板中的小模板
    # GET 请求渲染模板
    if request.method == 'GET':

        data = {
            'user': user.to_dict()
        }
        return render_template('news/user_base_info.html', data=data)
    # POST 请求修改数据
    # 一.获取参数
    nick_name = request.json.get('nick_name')
    gender = request.json.get('gender')
    signature = request.json.get('signature')

    # 二.校验参数
    if not all([nick_name, gender, signature]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    if gender not in ['MAN', 'WOMEN']:
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    # 三.逻辑处理
    # 修改数据模型
    user.nick_name = nick_name
    user.gender = gender
    user.signature = signature

    # 提交数据库
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库错误")

    # 设置session数据
    session['nick_name'] = nick_name

    # 四.返回数据
    return jsonify(errno=RET.OK, errmsg="更新成功")


@user_blue.route('/info')
@user_login_data
def info():
    user = g.user
    # 目前我们只需要在这里判断一次用户没登录. 因为如果咱们大的模板页面都无法加载, 小页面也是无法加载的
    if not user:
        return redirect('/')
    data = {
        'user': user.to_dict()
    }
    return render_template('news/user.html', data=data)
